#include "mainapp.h"
#include <iostream>
#include <libxml++/libxml++.h>
#include <sstream>
#include <string>
using namespace Gnome::Glade;
using namespace std;
Mapp::Mapp (int argc, char *argv[]):Gtk::Main (argc, argv), mmain (NULL),
	xdd ("savemoney.xml")
{

	ref_xml = Xml::create ("1.glade");

	ref_xml->get_widget ("window1", mmain);
	iim = ref_xml->get_widget ("image1", iim);
        iim->set("forg.png");
	xmlpp::Node * node = xdd.get_document ()->get_root_node ();
	nodeElement = dynamic_cast < xmlpp::Element * >(node);
	list = nodeElement->get_children ();
	ne = list.begin ();

	Gtk::Button * next = ref_xml->get_widget ("button1", next);
	Gtk::Button * del = ref_xml->get_widget ("button3", del);
	Gtk::Button * save = ref_xml->get_widget ("button2", save);
	save->set_sensitive(false);

	next->signal_clicked ().connect (sigc::mem_fun (*this, &Mapp::set));
	del->signal_clicked ().connect (sigc::mem_fun (*this, &Mapp::delimage));
	save->signal_clicked ().connect (sigc::mem_fun (*this, &Mapp::savedata));

	nextimage ();

}

Mapp::~Mapp ()
{
}

	void
Mapp::delimage ()
{
	
	dlist.push_back(*ne);
	nextimage();
}

	void
Mapp::savedata ()

{
	std::list<xmlpp::Node *>::iterator b = dlist.begin();
	
	xmlpp::Node * node = xdd.get_document ()->get_root_node ();
	nodeElement = dynamic_cast < xmlpp::Element * >(node);
        for(b;b!=dlist.end();b++)
	{
           nodeElement->remove_child(*b);
	}

	xdd.get_document()->write_to_file ("savemoney.xml");

	Gtk::Main::quit();
}

void Mapp::set()
{
	Gtk::Entry * e1 = ref_xml->get_widget ("entry1", e1);
	xmlpp::Element * nodeElement = NULL;
	nodeElement = dynamic_cast < xmlpp::Element * >(*ne);
        if(e1->get_text().empty())
	{
		return;
	}

	nodeElement->set_attribute("day",e1->get_text());
	nodeElement->remove_attribute("f1");
	nodeElement->remove_attribute("f2");
	nodeElement->remove_attribute("Logic");
	nodeElement->remove_attribute("image");
	nextimage();
}

	void
Mapp::nextimage ()
{
 
	xmlpp::Element * nodeElement = NULL;
	if(ne != list.end())
	{
	ne++;
	}
	while (true)
	{
		if (ne == list.end ())
		{
			Gtk::Button * save = ref_xml->get_widget ("button2", save);
			save->set_sensitive();
			Gtk::Button * next = ref_xml->get_widget ("button1", next);
			next->set_sensitive(false);

			return;
		}
		nodeElement = dynamic_cast < xmlpp::Element * >(*ne);
		if (nodeElement == NULL)
		{
			ne++;
			continue;
		}
		break;
	}
	iim->set (nodeElement->get_attribute_value ("image"));
       Gtk::Label * lb= ref_xml->get_widget ("label1", lb);
       lb->set_text(nodeElement->get_attribute_value ("begcorrect"));
}
	void
Mapp::show_window ()
{
	if (mmain)
		run (*mmain);
}
